package com.sqfw.project.wpReport.service.impl;

import com.github.pagehelper.PageInfo;
import com.sqfw.common.constant.HttpStatus;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.framework.web.page.TableDataInfo;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.utils.UpperItemUtils;
import com.sqfw.project.wp.domain.SysCode;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.domain.WpVisitInfo;
import com.sqfw.project.wp.mapper.*;
import com.sqfw.project.wpReport.domain.WpHoliday;
import com.sqfw.project.wpReport.mapper.WpHolidayMapper;
import com.sqfw.project.wpReport.service.ZJManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ Author：linchangchun
 * @ Date：2023-12-19-16:36
 * @ Version：1.0
 */
@Service
public class ZJManageServiceImpl implements ZJManageService {
    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private WpVisitInfoMapper wpVisitInfoMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper userMapper;


    @Autowired
    private WpHolidayMapper wpHolidayMapper;


    @Override
    public TableDataInfo getZJManageWpListAll(WpInfo wpInfo) throws ParseException {

        //全部工单，只查询已经归档的工单
        List<String> districtAll = wpInfo.getDistrictAll();
        //居委会查询
        if (StringUtils.isNotEmpty(districtAll)) {
            for (int i = 0; i < districtAll.size(); i++) {
                if (i == 0) {
                    //区域
                    wpInfo.setDistrict(districtAll.get(i));
                }
                if (i == 1) {
                    //街道
                    wpInfo.setStreet(districtAll.get(i));
                }
                if (i == 2) {
                    //居委会
                    wpInfo.setCommittee(districtAll.get(i));

                }
            }
        }
        //内容分类查询条件
        List<List<String>> classAllFind = wpInfo.getClassAllFind();

        //内容分类查询
        if (StringUtils.isEmpty(classAllFind)) {
            wpInfo.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            wpInfo.setClassAll(classAllCon);
        }
        String prop = wpInfo.getProp();
        String order = wpInfo.getOrder();
        String orderBy = UpperItemUtils.upperInfoName(order, prop);
        //排序字段
        String rowItem = UpperItemUtils.upperRowItem(prop);
        wpInfo.setRowItem(rowItem);


        wpInfo.setOrderBy(orderBy);
        if ("1".equals(wpInfo.getBackState())){
            wpInfo.setLastState("质检审核处理");
            wpInfo.setWhlNextState("坐席处理");
        }
        if (StringUtils.isNotEmpty(wpInfo.getIsAccountable())){
            if ("0".equals(wpInfo.getIsAccountable())){
                wpInfo.setIsAccountable("不等于");
            }
            if ("1".equals(wpInfo.getIsAccountable())){
                wpInfo.setIsAccountable("等于");
            }

        }
        List<String> wpids = wpInfoMapper.getManageWpListAll(wpInfo);
        List<WpInfo> wpInfos = new ArrayList<>();
        if (wpids.size() == 0) {
            return getDataTable(wpInfos, wpids);
        }
        for (String wpid : wpids) {
            WpInfo wpInfoCon = wpInfoMapper.selectWpInfoByWpId(wpid);
            //话务员真实姓名
            if (StringUtils.isNotEmpty(wpInfoCon.getSender())) {
                SysUser sysUser = userMapper.selectUserByCode(wpInfoCon.getSender());
                if (sysUser != null) {
                    wpInfoCon.setInitiatorName(sysUser.getNickName());
                }

            }

            if (StringUtils.isNotEmpty(wpInfo.getIssatisfied())) {
                wpInfoCon.setIssatisfied(wpInfo.getIssatisfied());
            } else {
                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(wpid);
                if (wpVisitInfo != null) {
                    wpInfoCon.setIssatisfied(wpVisitInfo.getIssatisfied());
                }
            }
            if (StringUtils.isNotEmpty(wpInfoCon.getDeptLevel2())) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(wpInfoCon.getDeptLevel2()));
                if (sysDept != null) {
                    wpInfoCon.setMainUnitName(sysDept.getDeptName());
                }

            }
            String class1 = wpInfoCon.getClass1();
            String class2 = wpInfoCon.getClass2();
            String class3 = wpInfoCon.getClass3();
            String class4 = wpInfoCon.getClass4();

            StringBuffer name = new StringBuffer();

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                if (sysCode != null) {
                    wpInfoCon.setMainNodename(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                if (sysCode != null) {
                    name.append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }

            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                if (sysCode != null) {
                    name.append("/").append(sysCode.getNodename());
                }
            }
            if (StringUtils.isNotEmpty(name)) {
                wpInfoCon.setChildNodeName(name.toString());
            }

            String cbdwComplete = wpInfoCon.getCbdwComplete();
            if (StringUtils.isNotEmpty(cbdwComplete)) {
                //已完成
                if (cbdwComplete.equals("1")) {
                    wpInfoCon.setResidue("已完成");
                } else if (cbdwComplete.equals("0")) {
                    // 老数据的处理方式--2025-09-10
                    if ("工单归档".equals(wpInfoCon.getNextState())) {
                        wpInfoCon.setResidue("已完成");
                    }else {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String timeBoundry = wpInfoCon.getTimeBoundry();
                        if (StringUtils.isNotEmpty(timeBoundry)) {
                            String residueDay = checkResidueDay(simpleDateFormat.parse(timeBoundry));
                            wpInfoCon.setResidue(residueDay);
                        }
                    }
                }
            }
            wpInfos.add(wpInfoCon);
        }
        return getDataTable(wpInfos, wpids);

    }

    /**
     * 检测剩余天数
     *
     * @return
     */
    private String checkResidueDay(Date date) throws ParseException {

        int day = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        long year = calendar.get(Calendar.YEAR);
        WpHoliday wpHoliday = new WpHoliday();
        wpHoliday.setYearid(year);
        List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);

        List<String> dates = wpHolidays.stream()
                .map(WpHoliday::getDtime)
                .map(simpleDateFormat::format)
                .collect(Collectors.toList());
        Date dateNew = new Date();
        String format = simpleDateFormat.format(dateNew);
        Date parse = simpleDateFormat.parse(format);
        String lasetDate = "";

        if (parse.compareTo(date) <= 0) {

            long now = date.getTime();
            long old = parse.getTime();
            long betweenDays = (now - old) / 24 / 60 / 60 / 1000;
            if (betweenDays == 0) {

            }
            for (int i = 0; i < betweenDays; i++) {
                lasetDate = addDay(parse, i);
                if (!dates.contains(lasetDate)) {
                    day++;
                }
            }
            return "剩余" + day + "天";
        } else {
            long now = date.getTime();
            long old = parse.getTime();
            long betweenDays = (old - now) / 24 / 60 / 60 / 1000;
            for (int i = 0; i <= betweenDays; i++) {
                lasetDate = addDay(date, i);
                if (!dates.contains(lasetDate)) {
                    day++;
                }
            }
            return "超时" + day + "天";

        }

    }

    /**
     * @param date 日期
     * @return 加算后的日期
     * @Description 参数的日期加指定的日
     */
    private String addDay(Date date, int day) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);

        return simpleDateFormat.format(calendar.getTime());
    }

    protected TableDataInfo getDataTable(List<?> list, List<?> total) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(total).getTotal());
        return rspData;
    }
}
